package com.mcode.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mcode.blog.dao.dos.Archives;
import com.mcode.blog.dao.mapper.ArticleBodyMapper;
import com.mcode.blog.dao.mapper.ArticleMapper;
import com.mcode.blog.dao.mapper.ArticleTagMapper;
import com.mcode.blog.dao.pojo.*;
import com.mcode.blog.service.*;
import com.mcode.blog.utils.UserThreadLocal;
import com.mcode.blog.vo.ArticleBodyVo;
import com.mcode.blog.vo.ArticleVo;
import com.mcode.blog.vo.TagVo;
import com.mcode.blog.vo.params.ArticleParam;
import com.mcode.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private TagService tagService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private ArticleBodyMapper articleBodyMapper;

    @Resource
    private CategoryService categoryService;

    @Resource
    private ThreadService threadService;

    @Resource
    private ArticleTagMapper articleTagMapper;


    @Override
    public List<ArticleVo> listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth()
        );
        return copyList(articleIPage.getRecords(), true, true);
    }

//    @Override
//    public List<ArticleVo> listArticle(PageParams pageParams) {
//        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//
//        // 分类id
//        if (pageParams.getCategoryId() != null) {
//            queryWrapper.eq(Article::getCategoryId, pageParams.getCategoryId());
//        }
//
//        // 标签id
//        List<Long> articleIds = new ArrayList<>();
//        if (pageParams.getTagId() != null) {
//            // 查找与标签id有关的文章id，添加到articleIds中
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId, pageParams.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIds.add(articleTag.getArticleId());
//            }
//
//            if (articleTags.size() > 0) {
//                queryWrapper.in(Article::getId, articleIds);
//            }
//        }
//
//        // 置顶排序 按时间排序 order by create_date desc
//        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
//
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//        List<Article> records = articlePage.getRecords();
//        return copyList(records, true, true);
//    }


    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor, false, false));
        }
        return articleVoList;
    }


    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-mm-dd HH"));

        if (isTag) {
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }

        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }

        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }

        if (isCategory) {
            Long cateId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(cateId));
        }

        return articleVo;
    }



    /**
     * 根据id返回文章内容
     *
     * @param bodyId
     * @return
     */
    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }


    @Override
    public List<ArticleVo> hotArticle(int limit) {
        return this.getLimitArticleByType(limit, "hot");
    }


    @Override
    public List<ArticleVo> newArticle(int limit) {
        return this.getLimitArticleByType(limit, "new");
    }


    /**
     * 根据类型获取指定数量文章数据
     *
     * @param limit
     * @param type
     * @return
     */
    public List<ArticleVo> getLimitArticleByType(int limit, String type) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        if (type.equals("hot")) {
            queryWrapper.orderByDesc(Article::getViewCounts);
        } else {
            queryWrapper.orderByDesc(Article::getId);
        }
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return copyList(articles, false, false);
    }


    /**
     * 文章归档
     *
     * @return
     */
    @Override
    public List<Archives> listArchives() {
        List<Archives> archives = articleMapper.selectListArchives();
        return archives;
    }


    /**
     * 根据id获取文章
     *
     * @param articleId
     * @return
     */
    @Override
    public ArticleVo findArticleById(Long articleId) {
        // 根绝id查询
        // 拼接返回文章vo
        Article article = articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true, true, true);
        // 新增阅读数
        // 线程池 可以吧更新操作 扔到线程池中取执行 和主线程不相关
        threadService.updateArticleViewCount(articleMapper, article);
        return articleVo;
    }


    @Override
    @Transactional
    public ArticleVo publish(ArticleParam articleParam) {
        /**
         * 1. 发布文章 目的 构建Article对象
         * 2. 作者id  当前的登录用户
         * 3. 标签  要将标签加入到 关联列表当中
         * 4. body 内容存储 article bodyId
         */
        // 当前登录用户信息
        SysUser sysUser = UserThreadLocal.get();
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setCreateDate(System.currentTimeMillis());
        article.setCommentCounts(0);
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setBodyId(-1L);
        articleMapper.insert(article);
        // 插入之后 会生成一个文章id（因为新建的文章没有文章id所以要insert一下
        // 官网解释："insart后主键会自动'set到实体的ID字段。所以你只需要"getid()就好
        // 利用主键自增，mp的insert操作后id值会回到参数对象中
        // https://blog.csdn.net/HSJ0170/article/details/107982866

        // tags
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(article.getId());
                articleTagMapper.insert(articleTag);
            }
        }

        // body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);

        //插入完之后再给一个id
        article.setBodyId(articleBody.getId());
        // MybatisPlus中的save方法什么时候执行insert，什么时候执行update
        // https://www.cxyzjd.com/article/Horse7/103868144
        // 只有当更改数据库时才插入或者更新，一般查询就可以了
        articleMapper.updateById(article);

        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        return articleVo;
    }

}
